package com.learning.assignment_1;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.List;

import com.facebook.AppEventsLogger;
import com.facebook.FacebookAuthorizationException;
import com.facebook.FacebookOperationCanceledException;
import com.facebook.FacebookRequestError;
import com.facebook.Request;
import com.facebook.Response;
import com.facebook.Session;
import com.facebook.Session.OpenRequest;
import com.facebook.Session.StatusCallback;
import com.facebook.SessionLoginBehavior;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.android.Facebook;
import com.facebook.model.GraphObject;
import com.facebook.model.GraphPlace;
import com.facebook.model.GraphUser;

import com.facebook.widget.*;
import com.learning.mycanvas.MyViewUsingCanvas;
import com.learning.mycanvas.MyViewUsingCanvas.DrawingObjects;
import com.learning.services.MySoundServices;
import com.learning.utils.*;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.View.OnLongClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
	public static enum State {
		None, Transform, Rotate, Edit, Load, Save, ImagePicking
	}

	float startx, starty;
	float lastzoom = 1;
	float startdrawingtoolx, startdrawingtooly;
	public State currentState = State.None;
	public String imgName = "";
	public boolean isAppearing = false;
	private static final int CAMERA_REQUEST = 1888;
	private MenuItem uploaditem;
	private boolean isposting = false;
	// Facebook variables

	Facebook authenticatedFacebook = new Facebook("473787926065598");

	private static final String[] PERMISSIONS = new String[] {
			"publish_stream", "read_stream", "offline_access" };

	private static final String PERMISSION = "publish_actions";
	private static final Location SEATTLE_LOCATION = new Location("") {
		{
			setLatitude(47.6097);
			setLongitude(-122.3331);
		}
	};

	private final String PENDING_ACTION_BUNDLE_KEY = "com.facebook.samples.hellofacebook:PendingAction";

	private Button postStatusUpdateButton;
	private Button postPhotoButton;
	private Button pickFriendsButton;
	private Button pickPlaceButton;
	private LoginButton loginButton;
	private ProfilePictureView profilePictureView;
	private TextView greeting;
	private PendingAction pendingAction = PendingAction.NONE;
	private ViewGroup controlsContainer;
	private GraphUser user;
	private GraphPlace place;
	private List<GraphUser> tags;
	private boolean canPresentShareDialog;
	private Context myContext;

	private enum PendingAction {
		NONE, POST_PHOTO, POST_STATUS_UPDATE
	}

	private UiLifecycleHelper uiHelper;

	private Session.StatusCallback callback = new Session.StatusCallback() {
		@Override
		public void call(Session session, SessionState state,
				Exception exception) {
			onSessionStateChange(session, state, exception);
		}
	};

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);

		if (requestCode == FILE_SELECT_CODE) {
			if (resultCode == RESULT_OK) {
				// Get the Uri of the selected file
				Uri uri = data.getData();

				Bitmap bitmap;
				try {
					Bitmap bm = null;
					BitmapFactory.Options options = new BitmapFactory.Options();
					options.inSampleSize = 1;
					AssetFileDescriptor fileDescriptor = null;
					try {
						fileDescriptor = this.getContentResolver()
								.openAssetFileDescriptor(uri, "r");
					} catch (FileNotFoundException e) {
						e.printStackTrace();
					} finally {
						try {
							bm = BitmapFactory.decodeFileDescriptor(
									fileDescriptor.getFileDescriptor(), null,
									options);
							fileDescriptor.close();
						} catch (IOException e) {
							e.printStackTrace();
						}
					}

					iv.drawImage(bm);
					// bm.recycle();
				} catch (Exception ex) {
					Log.d("bug ngu hoc", ex.getMessage().toString());
				}
			}
		} else if (requestCode == CAMERA_REQUEST) {
			if (resultCode == RESULT_OK) {
				Bitmap photo = (Bitmap) data.getExtras().get("data");
				iv.drawImage(photo);
				photo.recycle();
			}

		} else
			uiHelper.onActivityResult(requestCode, resultCode, data,
					dialogCallback);
	}

	private FacebookDialog.Callback dialogCallback = new FacebookDialog.Callback() {
		@Override
		public void onError(FacebookDialog.PendingCall pendingCall,
				Exception error, Bundle data) {
			Log.d("HelloFacebook", String.format("Error: %s", error.toString()));
		}

		@Override
		public void onComplete(FacebookDialog.PendingCall pendingCall,
				Bundle data) {
			Log.d("HelloFacebook", "Success!");
		}
	};

	private void onSessionStateChange(Session session, SessionState state,
			Exception exception) {
		updateUI();
	}

	// @Override
	// public void onCreate(Bundle savedInstanceState) {
	// super.onCreate(savedInstanceState);
	// uiHelper = new UiLifecycleHelper(this, callback);
	// uiHelper.onCreate(savedInstanceState);
	//
	// setContentView(R.layout.main);
	//
	// // Add code to print out the key hash
	// try {
	// PackageInfo info = getPackageManager().getPackageInfo(
	// "com.facebook.samples.hellofacebook",
	// PackageManager.GET_SIGNATURES);
	// for (Signature signature : info.signatures) {
	// MessageDigest md = MessageDigest.getInstance("SHA");
	// md.update(signature.toByteArray());
	// Log.d("KeyHash:", Base64.encodeToString(md.digest(), Base64.DEFAULT));
	// }
	// } catch (NameNotFoundException e) {
	//
	// } catch (NoSuchAlgorithmException e) {
	//
	// }
	//
	//
	// loginButton = (LoginButton) findViewById(R.id.login_button);
	// loginButton.setUserInfoChangedCallback(new
	// LoginButton.UserInfoChangedCallback() {
	// @Override
	// public void onUserInfoFetched(GraphUser user) {
	// MainActivity.this.user = user;
	// updateUI();
	// // It's possible that we were waiting for this.user to be populated in
	// order to post a
	// // status update.
	//
	// // handlePendingAction();
	// }
	// });
	//
	// profilePictureView = (ProfilePictureView)
	// findViewById(R.id.profilePicture);
	// }

	// //////////////////////////////////
	
	private void OpenSession(){
		OpenRequest open = new OpenRequest(this);
        open.setLoginBehavior(SessionLoginBehavior.SSO_WITH_FALLBACK); 
        open.setPermissions(Arrays.asList(new String[]{"email", "publish_actions", "user_birthday", "user_hometown"}));
        open.setCallback(new StatusCallback() {
			
			@Override
			public void call(Session session, SessionState state, Exception exception) {
				// TODO Auto-generated method stub
				Toast.makeText(myContext, "Session is opened", Toast.LENGTH_LONG).show();
			}
		});    
//        Session s = new Session(this);
        Session s = Session.getActiveSession();
        if (s == null || s.getState().isClosed()) 
        {
            Session session = new Session.Builder(this).build();
            Session.setActiveSession(session);
            s = session;
        }

        s.openForPublish(open);
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		uiHelper = new UiLifecycleHelper(this, callback);
		uiHelper.onCreate(savedInstanceState);

		// this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_main);
		
		
	

		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		iv = new MyViewUsingCanvas(this, main);
		DisplayMetrics displaymetrics = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(displaymetrics);
		int screenWidth = displaymetrics.widthPixels;
		int screenHeight = displaymetrics.heightPixels;
		RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
				screenWidth - 20, screenHeight - 110);
		rlp.leftMargin = 10;
		rlp.topMargin = 80;
		rlp.bottomMargin = 80;
		rlp.rightMargin = 10;

		// startService(new Intent(this,MySoundServices.class));

		iv.setCurrentState(State.Edit);
		main.addView(iv, rlp);
		iv.createNewMatrix();
		initializeDrawingTool();

		myContext = this;

		ImageButton fbbtn = (ImageButton) findViewById(R.id.fbbtn);

		fbbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Session ss = Session.getActiveSession();
				if (ss == null || !ss.isOpened())
					OpenSession();
				
				if (!isposting)
					addPostFbView();
				else
					removePostFbView();
				isposting = !isposting;
			}
		});

		profilePictureView = (ProfilePictureView) findViewById(R.id.profilePicture);

		ImageButton savebtn = (ImageButton) findViewById(R.id.savebtn);
		savebtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				saveImage();
			}

		});

		ImageButton newbtn = (ImageButton) findViewById(R.id.newbtn);
		newbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				iv.newEditor();
			}
		});
	}

	private void updateUI() {
		if (uploaditem != null) {
			uploaditem.setEnabled(Session.getActiveSession().isOpened());
		}
	}

	private void addPostFbView() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final LinearLayout fbview = (LinearLayout) inflater.inflate(
				R.layout.post_fb_view, null);
		fbview.setId(MyConstants.POST_FB_VIEW);

		RelativeLayout.LayoutParams rlp = new RelativeLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
		rlp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM);
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		Animation upanim = AnimationUtils.loadAnimation(this,
				R.anim.slideupanim);
		main.addView(fbview, rlp);

		fbview.startAnimation(upanim);
		
		Button postbtn = (Button) findViewById(R.id.submit_btn);
		postbtn.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				EditText et = (EditText) fbview.findViewById(R.id.fbstatus);
				postPhoto(et.getText().toString());
				removePostFbView();
				InputMethodManager imm = (InputMethodManager) myContext.getSystemService(Context.INPUT_METHOD_SERVICE);
				imm.hideSoftInputFromWindow(et.getWindowToken(), 0);
			}
		});
	}

	private void removePostFbView(){
		Animation upanim = AnimationUtils.loadAnimation(this, R.anim.slidedownanim);
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		LinearLayout fbview = (LinearLayout) main
				.findViewById(MyConstants.POST_FB_VIEW);
		
		fbview.startAnimation(upanim);
		main.removeView(fbview);
	}

	private boolean hasPublishPermission() {
		Session session = Session.getActiveSession();
		return session != null
				&& session.getPermissions().contains("publish_actions");
	}

	private void postPhoto(String msg) {
		if (hasPublishPermission()) {
			Bitmap returnedBitmap = Bitmap.createBitmap(iv.getWidth(),
					iv.getHeight(), Bitmap.Config.ARGB_8888);
			Canvas canvas = new Canvas(returnedBitmap);
			Drawable bgDrawable = iv.getBackground();
			if (bgDrawable != null)
				bgDrawable.draw(canvas);
			else
				canvas.drawColor(Color.WHITE);
			iv.draw(canvas);
			Request request = Request.newUploadPhotoRequest(
					Session.getActiveSession(), returnedBitmap,
					new Request.Callback() {
						@Override
						public void onCompleted(Response response) {
							showPublishResult("Photo post",
									response.getGraphObject(),
									response.getError());
						}
					});
			Bundle params = request.getParameters();
			params.putString("message", msg);
			request.executeAsync();
		} else {
			pendingAction = PendingAction.POST_PHOTO;
		}
	}

	private interface GraphObjectWithId extends GraphObject {
		String getId();
	}

	private void showPublishResult(String message, GraphObject result,
			FacebookRequestError error) {
		String title = null;
		String alertMessage = null;
		if (error == null) {
			title = getString(R.string.success);
			String id = result.cast(GraphObjectWithId.class).getId();
			alertMessage = getString(R.string.successfully_posted_post,
					message, id);
		} else {
			title = getString(R.string.error);
			alertMessage = error.getErrorMessage();
		}

		new AlertDialog.Builder(this).setTitle(title).setMessage(alertMessage)
				.setPositiveButton(R.string.ok, null).show();
	}

	// //////////////////////////////////////////////////////////////////////////////

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, 2, 1, "Rotate").setIcon(R.drawable.rotate);
		menu.add(0, 3, 2, "Transform").setIcon(R.drawable.move);
		menu.add(0, 4, 3, "Draw").setIcon(R.drawable.edit);
		// menu.add(0, 5, 4, "Add").setIcon(R.drawable.newimage);
		menu.add(0, 6, 5, "Add Image").setIcon(R.drawable.load);
		// menu.add(0, 7, 6, "Save").setIcon(R.drawable.save);
		menu.add(0, 8, 7, "Image Picker");
		menu.add(0, 9, 8, "Galery");
		menu.add(0, 10, 9, "Upload to Facebook");

		// uploaditem = menu.getItem(9);
		// uploaditem.setEnabled(Session.getActiveSession().isOpened());
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		main.removeView(main.findViewById(MyConstants.DRAWINGTOOLID));
		main.removeView(main.findViewById(MyConstants.ZOOMID));
		switch (item.getItemId()) {
		case 2:
			iv.setCurrentState(State.Rotate);
			break;
		case 3:
			iv.setCurrentState(State.Transform);
			initializeZoomTool();
			break;
		case 4:
			iv.setCurrentState(State.Edit);
			iv.createNewMatrix();
			initializeDrawingTool();
			break;
		case 5:
			// TO DO: create new image
			iv.newEditor();
			break;
		case 6:
			// iv.setCurrentState(State.Load);
			// showFileChooser();
			addnewImage();
			break;
		case 7:
			saveImage();
			break;
		case 8:
			iv.setCurrentState(State.ImagePicking);
			break;
		case 9:
			Intent intent = new Intent(MainActivity.this, GaleryActivity.class);
			startActivity(intent);
			break;
		case 10:
			break;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void addnewImage() {
		LayoutInflater factory = LayoutInflater.from(this);
		final View dlgView = factory.inflate(R.layout.add_image_dialog, null);
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		dlg.setView(dlgView);

		dlgView.findViewById(R.id.btnImageOK).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						RadioGroup rdcamera = (RadioGroup) dlgView
								.findViewById(R.id.radionewImage);
						if (rdcamera.getCheckedRadioButtonId() == R.id.radioCamera) {
							Intent cameraIntent = new Intent(
									android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(cameraIntent, CAMERA_REQUEST);

						} else {
							showFileChooser();
						}
						dlg.dismiss();

					}
				});
		dlg.show();

	}

	public void saveImage() {

		LayoutInflater factory = LayoutInflater.from(this);
		final View dlgView = factory.inflate(R.layout.savedialog, null);
		final AlertDialog dlg = new AlertDialog.Builder(this).create();
		dlg.setView(dlgView);
		dlgView.findViewById(R.id.save_dialog_ok).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						// your business logic
						EditText txt = (EditText) dlgView
								.findViewById(R.id.pictureName);
						imgName = txt.getText().toString();
						if (imgName != "") {
							Bitmap returnedBitmap = Bitmap.createBitmap(
									iv.getWidth(), iv.getHeight(),
									Bitmap.Config.ARGB_8888);
							Canvas canvas = new Canvas(returnedBitmap);
							Drawable bgDrawable = iv.getBackground();
							if (bgDrawable != null)
								bgDrawable.draw(canvas);
							else
								canvas.drawColor(Color.WHITE);
							iv.draw(canvas);

							FileOutputStream out;
							try {
								File dir = new File(Environment
										.getExternalStorageDirectory()
										+ "/MyGallery");
								if (!dir.exists() || (!dir.isDirectory())) {
									dir.mkdir();
								}

								out = new FileOutputStream("/sdcard/MyGallery/"
										+ imgName + ".jpeg");
								Bitmap returnedBitmap1 = Bitmap.createBitmap(
										iv.getWidth(), iv.getHeight(),
										Bitmap.Config.ARGB_8888);
								returnedBitmap.compress(
										Bitmap.CompressFormat.JPEG, 100, out);
								try {
									out.close();
								} catch (IOException e) {
									// TODO Auto-generated catch block
									e.printStackTrace();
								}
								imgName = "";
							} catch (FileNotFoundException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}

						}
						dlg.dismiss();
					}
				});
		dlgView.findViewById(R.id.save_dialog_cancel).setOnClickListener(
				new OnClickListener() {

					@Override
					public void onClick(View v) {
						dlg.dismiss();
					}
				});

		dlg.show();

	}

	private void initializeZoomTool() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final RelativeLayout zoomTool = (RelativeLayout) inflater.inflate(
				R.layout.zoom_toolbar, null);
		zoomTool.setId(MyConstants.ZOOMID);
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lp.leftMargin = 10;
		lp.topMargin = 100;
		main.addView(zoomTool, lp);

		SeekBar sb = (SeekBar) findViewById(R.id.customSizeView);
		sb.setMax(6);
		sb.setProgress(3);
		sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
			@Override
			public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
				DisplayMetrics displaymetrics = new DisplayMetrics();
				getWindowManager().getDefaultDisplay().getMetrics(
						displaymetrics);
				int screenWidth = displaymetrics.widthPixels;
				int screenHeight = displaymetrics.heightPixels;
				float zoom = 1;
				switch (i) {
				case 0:
					zoom = 0.25f;
					break;
				case 1:
					zoom = 0.5f;
					break;
				case 2:
					zoom = 0.75f;
					break;
				case 3:
					zoom = 1f;
					break;
				case 4:
					zoom = 1.5f;
					break;
				case 5:
					zoom = 2f;
					break;
				case 6:
					zoom = 2.5f;
					break;
				}
				iv.zoom(1 / lastzoom, (float) screenWidth / 2,
						(float) screenHeight / 2);
				iv.zoom(zoom, (float) screenWidth / 2, (float) screenHeight / 2);
				lastzoom = zoom;
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// NO-OP
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// NO-OP
			}
		});
	}

	private void initializeDrawingTool() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final LinearLayout drawingTool = (LinearLayout) inflater.inflate(
				R.layout.drawing_tool_bar, null);
		drawingTool.setId(MyConstants.DRAWINGTOOLID);
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		// lp.topMargin = 80;
		main.addView(drawingTool, lp);
		// final LinearLayout drawingTool = (LinearLayout)
		// findViewById(R.id.drawing_tool_bar_id);
		// drawingTool.bringToFront();
		// drawingTool.setVisibility(View.VISIBLE);
		lp = (RelativeLayout.LayoutParams) drawingTool.getLayoutParams();
		ImageButton pencil = (ImageButton) findViewById(R.id.pencil);
		pencil.setOnClickListener(drawingButtonListener);
		ImageButton eraser = (ImageButton) findViewById(R.id.eraser);
		eraser.setOnClickListener(drawingButtonListener);
		ImageButton line = (ImageButton) findViewById(R.id.line);
		line.setOnClickListener(drawingButtonListener);
		ImageButton rectangle = (ImageButton) findViewById(R.id.rectangle);
		rectangle.setOnClickListener(drawingButtonListener);
		ImageButton circle = (ImageButton) findViewById(R.id.circle);
		circle.setOnClickListener(drawingButtonListener);
		ImageButton colorPainter = (ImageButton) findViewById(R.id.colorpainter);
		colorPainter.setOnClickListener(drawingButtonListener);

		final Button textbtn = (Button) findViewById(R.id.textbtn);
		textbtn.setPaintFlags(textbtn.getPaintFlags()
				| Paint.UNDERLINE_TEXT_FLAG);

		textbtn.setOnClickListener(drawingButtonListener);
	}

	private void initializeColorPicker() {
		LayoutInflater inflater = LayoutInflater.from(this);
		final LinearLayout colorPicker = (LinearLayout) inflater.inflate(
				R.layout.color_picker, null);
		colorPicker.setId(MyConstants.COLORPICKERID);
		RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);
		RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(
				LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
		lp.topMargin = 150;
		main.addView(colorPicker, lp);
		// final LinearLayout colorPicker = (LinearLayout)
		// findViewById(R.id.color_picker_id);
		// colorPicker.bringToFront();
		// colorPicker.setVisibility(View.VISIBLE);

		Button redBtn = (Button) findViewById(R.id.redColorButton);
		redBtn.setOnClickListener(colorPickerListener);
		Button orangeBtn = (Button) findViewById(R.id.orangeColorButton);
		orangeBtn.setOnClickListener(colorPickerListener);
		Button yellowBtn = (Button) findViewById(R.id.yellowColorButton);
		yellowBtn.setOnClickListener(colorPickerListener);
		Button greenBtn = (Button) findViewById(R.id.greenColorButton);
		greenBtn.setOnClickListener(colorPickerListener);
		Button blueBtn = (Button) findViewById(R.id.blueColorButton);
		blueBtn.setOnClickListener(colorPickerListener);
		Button indigoBtn = (Button) findViewById(R.id.indigoColorButton);
		indigoBtn.setOnClickListener(colorPickerListener);
		Button purpleBtn = (Button) findViewById(R.id.purpleColorButton);
		purpleBtn.setOnClickListener(colorPickerListener);
		Button blackBtn = (Button) findViewById(R.id.blackColorButton);
		blackBtn.setOnClickListener(colorPickerListener);

	}

	private OnClickListener colorPickerListener = new OnClickListener() {
		@Override
		public void onClick(View arg0) {
			ImageButton colorpainter = (ImageButton) findViewById(R.id.colorpainter);
			RelativeLayout main = (RelativeLayout) findViewById(R.id.mainLayout);

			switch (arg0.getId()) {
			case R.id.redColorButton:
				iv.setColorPainter(Color.parseColor("#cc0000"));
				colorpainter.setBackgroundColor(Color.parseColor("#cc0000"));
				break;
			case R.id.orangeColorButton:
				iv.setColorPainter(Color.parseColor("#ffa500"));
				colorpainter.setBackgroundColor(Color.parseColor("#ffa500"));
				break;
			case R.id.yellowColorButton:
				iv.setColorPainter(Color.parseColor("#ffff00"));
				colorpainter.setBackgroundColor(Color.parseColor("#ffff00"));
				break;
			case R.id.greenColorButton:
				iv.setColorPainter(Color.parseColor("#008000"));
				colorpainter.setBackgroundColor(Color.parseColor("#008000"));
				break;
			case R.id.blueColorButton:
				iv.setColorPainter(Color.parseColor("#0000ff"));
				colorpainter.setBackgroundColor(Color.parseColor("#0000ff"));
				break;
			case R.id.indigoColorButton:
				iv.setColorPainter(Color.parseColor("#4b0082"));
				colorpainter.setBackgroundColor(Color.parseColor("#4b0082"));
				break;
			case R.id.purpleColorButton:
				iv.setColorPainter(Color.parseColor("#800080"));
				colorpainter.setBackgroundColor(Color.parseColor("#800080"));
				break;
			case R.id.blackColorButton:
				iv.setColorPainter(Color.parseColor("#000000"));
				colorpainter.setBackgroundColor(Color.parseColor("#000000"));
				break;
			default:
				break;
			}
			// findViewById(R.id.color_picker_id).setVisibility(View.GONE);
			main.removeView(main.findViewById(MyConstants.COLORPICKERID));
		}
	};

	public void getColor() {
		new ColorPicker(this, new ColorPicker.OnColorChangedListener() {

			@Override
			public void colorChanged(int color) {
				// TODO Auto-generated method stub
				ImageButton clpk = (ImageButton) findViewById(R.id.colorpainter);
				clpk.setBackgroundColor(color);
				iv.setColorPainter(color);
			}
		}, Color.BLACK).show();
	}

	private OnClickListener drawingButtonListener = new OnClickListener() {

		@Override
		public void onClick(View arg0) {
			// TODO Auto-generated method stub
			ImageButton pencil = (ImageButton) findViewById(R.id.pencil);
			pencil.setBackgroundColor(Color.TRANSPARENT);
			ImageButton eraser = (ImageButton) findViewById(R.id.eraser);
			eraser.setBackgroundColor(Color.TRANSPARENT);
			ImageButton line = (ImageButton) findViewById(R.id.line);
			line.setBackgroundColor(Color.TRANSPARENT);
			ImageButton rectangle = (ImageButton) findViewById(R.id.rectangle);
			rectangle.setBackgroundColor(Color.TRANSPARENT);
			ImageButton circle = (ImageButton) findViewById(R.id.circle);
			circle.setBackgroundColor(Color.TRANSPARENT);
			Button textbtn = (Button) findViewById(R.id.textbtn);
			textbtn.setBackgroundColor(Color.TRANSPARENT);

			if (arg0.getId() != R.id.colorpainter)
				arg0.setBackgroundColor(Color.GRAY);

			switch (arg0.getId()) {
			case R.id.pencil:
				iv.setDrawnObject(MyViewUsingCanvas.DrawingObjects.Pencil);
				break;
			case R.id.eraser:
				iv.setDrawnObject(MyViewUsingCanvas.DrawingObjects.Eraser);
				break;
			case R.id.line:
				iv.setDrawnObject(MyViewUsingCanvas.DrawingObjects.Line);
				break;
			case R.id.rectangle:
				iv.setDrawnObject(MyViewUsingCanvas.DrawingObjects.Rectangle);
				break;
			case R.id.circle:
				iv.setDrawnObject(MyViewUsingCanvas.DrawingObjects.Circle);
				break;
			case R.id.colorpainter:
				getColor();
				break;
			case R.id.textbtn:
				iv.setDrawnObject(DrawingObjects.Text);
				break;
			default:
				break;
			}
		}

	};

	private static final int FILE_SELECT_CODE = 0;
	private MyViewUsingCanvas iv;

	private void showFileChooser() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.setType("*/*");
		intent.addCategory(Intent.CATEGORY_OPENABLE);

		try {
			startActivityForResult(
					Intent.createChooser(intent, "Select a File to Upload"),
					FILE_SELECT_CODE);
		} catch (android.content.ActivityNotFoundException ex) {
			// Potentially direct the user to the Market with a Dialog
			Toast.makeText(this, "Please install a File Manager.",
					Toast.LENGTH_SHORT).show();
		}
	}

	Matrix imageViewMatrix = new Matrix();

}
